package it.wyx.kafkaclients.consumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import javax.swing.*;

/**
 * 独立消费者案例（订阅分区）
 *
 * @author wyx
 * @version V 1
 * @Date 2022/10/30
 */
public class ConsumerSubscribePartition {
    private static final String BROKER_LIST = "localhost:9092";
    private static final String TOPIC = "test-topic";
    private static final String GROUP_ID = "test-group";

    public static void main(String[] args) {
        // 1.创建消费者的配置对象
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        // 设置消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);

        // 2、创建消费者客户端实例
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        // 3、消费某个主题的某个分区数据
        consumer.assign(Collections.singletonList(new TopicPartition(TOPIC, 1)));


        // 4、拉取数据打印
        while (true) {
            // 设置 1s 中消费一批数据
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(3000));
            System.out.println("接收消费records");
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record);
            }

//             System.out.println("Partition: " + partition.partition() + ", Committed Offset: " + committed.offset());
        }
    }
}
